<template>
    <div style="background-color: #fff;">
      <main-layout>
        <div class="plantFormBox">

            <div class="formItem">
                <h5>目标：</h5>
                <div class="inputItem">
                    <div class="lable"><span>*</span>每亩产量目标：</div>
                    <el-input v-model="formdata.yield" placeholder="输入平均每亩的产量目标" style="width: 300px;"/>
                    <div style="margin-left: 4px;">kg</div>
                </div>
            </div>

            <div class="formItem">
                <h5>作物品种：</h5>
                <div class="mytips">提示：需要考虑地理条件、亩产的潜力、生长周期、水资源需求、土壤要求、病虫害抗性、市场需求和价格、承受风险能力、 经验和知识、可持续性考虑。</div>
                <div class="inputItem">
                    <div class="lable"><span>*</span>选择作物：</div>
                    <div>
                        <!-- <el-select class="small-el-input__inner" popper-class="samll-el-select-dropdown__list" v-model="formdata.nongchang" clearable placeholder="选择作物">
                            <el-option :value="1" label="作物1" />
                            <el-option :value="2" label="作物2" />
                        </el-select> -->
                        <crop-select v-model="formdata.cropId" width="200px"/>
                    </div>
                    <div style="margin-left: 10px;">
                        <el-input v-model="formdata.category" placeholder="填写品种" style="width: 300px;"/>
                    </div>
                </div>
            </div>

            <div class="formItem" v-for="dt in stages" :key="dt.stageId">
                <h5>
                    {{dt.stageName}}：
                    <!-- <span>共计 3 块地，48.8 亩</span> -->
                </h5>
                <div class="mytips">提示：{{dt.stageDesc}}</div>
                <table class="itemTableBox">
                    <tr>
                        <th width="50">序号</th>
                        <th width="150">选择地块<span>*</span></th>
                        <th width="250">
                            <div class="tbItemFlex">
                                <div style="flex: 1;">农事事项<span>*</span></div>
                                <div><el-icon color="#48b27a" :size="16" @click="setFarmItem(dt)"><Plus /></el-icon></div>
                            </div> 
                        </th>
                        <th width="150">描述事项<span>*</span></th>
                        <th width="100">预算费用(元)</th>
                        <th width="250">负责人<span>*</span></th>
                        <th width="310">完成日期<span>*</span></th>
                        <th width="100">操作</th>
                    </tr>
                    <tr v-for="(dt2,index) in dt.lineList" :key="dt.stageId+'-'+index">
                        <td>{{index+1}}</td>
                        <td>
                            <el-input v-model="dt2.farmLandName" placeholder="点击添加地块" suffix-icon="Operation" readonly style="width: 150px;" @click="openSelectDg(dt,dt2)"/>
                        </td>
                        <td>
                            <task-select v-if="!dialogFlag" v-model="dt2.stageTaskId" :params="{stageId:dt.stageId}"/>
                            <el-select v-else clearable placeholder="" style="width:100%" class="small-el-input__inner" popper-class="samll-el-select-dropdown__list"></el-select>
                        </td>
                        <td>
                            <el-input v-model="dt2.taskContent" placeholder="点击添加事项描述" suffix-icon="Operation" readonly style="width: 150px;" @click="setTaskCon(dt,dt2)"/>
                        </td>
                        <td>
                            <el-input v-model="dt2.budgetFee" style="width: 100px;"/>
                        </td>
                        <td>
                            <user-select v-if="userList" :optLists="userList" v-model="dt2.fuzeUserIds" :multiple="true" placeholder="选择负责人"/>
                        </td>
                        <td>
                            <el-date-picker v-model="dt2.time" class="mydaterange" type="datetimerange" range-separator="-" start-placeholder="开始时间"
              end-placeholder="结束时间" value-format="YYYY-MM-DD HH:mm:ss"/>
                        </td>
                        <td>
                            <div class="tbItemFlex">
                                <el-icon v-if="index==0" color="#48b27a" :size="20" @click="dt.lineList.push({})"><CirclePlus /></el-icon>
                                <el-icon v-if="(dt2.taskStatus=='UN_CONFIRM') || (!dt2.taskStatus && index!=0)" color="#f82e2e" :size="20" @click="delLineListItem(dt.lineList,index)"><Remove /></el-icon>
                                <span v-if="dt2.taskStatus!='UN_CONFIRM'" style="color: #b90808;">{{dt2.taskStatusMeaning}}</span>
                            </div>
                        </td>
                    </tr>
                </table>
            </div>
            <div class="cbjs">合计预算成本：<b>{{totalCost}}</b>元</div>
            <div style="padding: 20px 0 0 0;">
                <el-button type="primary" @click="save">保存</el-button>
              <el-button @click="close">取消</el-button>
            </div>
        </div>
        <c-dialog v-model:show="dialogFlag" v-if="dialogFlag" :title="dialogInfo.title" :showBtn="false" @close="dialogFlag=false" :width="dialogInfo.width">
            <add-farming v-if="dialogInfo.type==1" :stagesItem="dialogInfo.options" @close="dialogFlag=false"/>
            <task-content v-else-if="dialogInfo.type==2" :options="dialogInfo.options" @close="dialogFlag=false"/>
            <del-reason v-else-if="dialogInfo.type==3" :options="dialogInfo.options" @close="dialogFlag=false"/>
            <farm-land-select v-else-if="dialogInfo.type==4" :options="dialogInfo.options" @close="dialogFlag=false"/>
        </c-dialog>
      </main-layout>
  
    </div>
  </template>
  
  <script setup name="Plant-Plan-Add">
  // 这里的name是为了做页面缓存，其值要跟路由里面的name值一样
  
  import { nextTick, ref, reactive,watch, onActivated,onMounted,computed} from 'vue'
  import{useRouter,useRoute} from "vue-router"

  import {getTaskList,getStageList,addFarmPlant,getPlantDetail,getDropdownList,editFarmPlant} from '@/api/plant'
  import {getUserList} from '@/api/system'

  import { useUserStore } from '@/pinia/modules/user'
  import { emitter } from '@/utils/bus.js'
  import mainLayout from '@/components/custom/mainLayout.vue'
  import taskSelect from '@/components/custom/taskSelect.vue'
  import userSelect from '@/components/custom/userSelect.vue'
  import landGroupSelect from '@/components/custom/landGroupSelect.vue'
  import cropSelect from '@/components/custom/cropSelect.vue'
  import cDialog from '@/components/custom/cDialog.vue'
  import addFarming from './components/addFarming.vue'
  import taskContent from './components/taskContent.vue'
  import delReason from './components/delReason.vue'
  import farmLandSelect from './components/farmLandSelect.vue'
  import { message } from '@/utils/element'
 

  const router = useRouter()
  const route = useRouter()
  const userStore = useUserStore()
  
  const formdata = ref({})
  const time = ref(null)
  const lgsRef = ref(null)
  const userList = ref('') 
  const stages = ref([]) // 种植阶段数据
  const plantHeaderId = ref('')
  let tmLists = []
  let landSelectData = ref([])
  let landLists = ref([])
  const dialogFlag = ref(false)
  const dialogInfo = ref({
    title:'标题',
    type:1  // 类型：1添加事项
  })

  onMounted(async ()=>{
    plantHeaderId.value = route.currentRoute.value.query.id

    getStageList({page: 1, limit: 100}).then(res=>{
        res.data.forEach(item => {
            // 为每一项添加任务列表
            if(plantHeaderId.value){  // 编辑
                item.lineList = []
            }else{// 新增时
                item.lineList = [{}] // 默认添加一行
            }
        });
        stages.value = res.data
    })

    //const res2 = await getUserList({page: 1, limit: 100})
    //userList.value = res2.data

    const res2 = await getDropdownList({page: 1, limit: 10,lovCode:'TANC_USER',param2:userStore.userInfo.companyId})
    userList.value = res2.data

    // 编辑处理
    await nextTick()
    if(plantHeaderId.value){
        document.title = '编辑种植计划-种植生产管理智能决策系统'
        getPlantDetail(plantHeaderId.value).then(res =>{
            formdata.value.yield = res.data.yield
            formdata.value.category = res.data.category
            formdata.value.cropId = res.data.cropId
            

            // 回显阶段任务信息
            res.data.lineRspList.forEach(item =>{
                const stagesItem = stages.value.find(ele =>ele.stageId == item.stageId)  // 查找种植阶段
                // 处理地块
                let lineLandIdList =[]
                let farmLandNames = []
                item.lineLandRspList.forEach(ele =>{
                    lineLandIdList.push(ele.farmLandId)
                    farmLandNames.push(ele.farmLandName)
                })
                // 处理负责人
                let fuzeUserIds = []
                item.fuzeUserList.forEach(ele =>{
                    fuzeUserIds.push(ele.fuzeUserId.toString())
                })

                let obj = {
                    plantLineId:item.plantLineId,
                    lineLandIdList, // 地块id列表
                    stageTaskId:item.stageTaskId, // 事项（任务）id
                    taskContent:item.taskContent, // 描述事项
                    budgetFee:item.budgetFee.amount, // 预算费用
                    fuzeUserIds, // 负责人id列表
                    time:[item.taskStartTime,item.taskEndTime], // 完成日期
                    taskStatus:item.taskStatus || '',
                    taskStatusMeaning:item.taskStatusMeaning,
                    reason:item.reason || '',
                    farmId:item.farmId,
                    farmLandName:farmLandNames.join('、'),
                    landDetailLists:item.lineLandRspList // 地块详情列表
                }
                stagesItem.lineList.push(obj)
            })
            // 查看是否有空的，为空就加一行
            stages.value.forEach(item => {
                if(item.lineList.length<1){  // 编辑
                    item.lineList = [{}]
                }
            });
        })
    }

  })

  const totalCost = ref(0)
  totalCost.value = computed(()=>{
    let total = 0
    for(let i=0;i<stages.value.length;i++){
        const item = stages.value[i]
        if(item.lineList){
            for(let j=0;j<item.lineList.length;j++){
                const item2 = item.lineList[j]
                if(item2.budgetFee && !isNaN(item2.budgetFee)){
                    total +=parseFloat(item2.budgetFee)
                }
            }
        }
        
    }
    return total
  })
  
  const setFarmItem = (stagesItem)=>{
    dialogFlag.value = true
    dialogInfo.value.title = "添加农事事项"
    dialogInfo.value.type = 1
    dialogInfo.value.options = stagesItem
    dialogInfo.value.width = '500px'
  }

  const setTaskCon = (stagesItem,lineListItem)=>{
    dialogFlag.value = true
    dialogInfo.value.title = "事项描述（1000字以内）"
    dialogInfo.value.type = 2
    dialogInfo.value.options = {stagesItem,lineListItem}
    dialogInfo.value.width = '700px'
  }
 
  const getSelectData = async (lists)=>{
    console.log("&&&&&:",lists)
    tmLists = JSON.parse(JSON.stringify(lists))
  }
  // 确认添加地块
  const comfirmSelectData = ()=>{
    if(landLists.value.length<1){
        return message('请选择地块',3) 
    }
    landSelectData.value = [...landSelectData.value,...tmLists]
    landLists.value = [] // 清空所选
    lgsRef.value.setDisabledItem(landSelectData.value)  // 设置不可选状态
  }
  // 删除选择的地块
  const delLandSelect = (index)=>{
    landSelectData.value.splice(index,1)
    lgsRef.value.setDisabledItem(landSelectData.value)  // 设置不可选状态
  }

  const save = async ()=>{
    formdata.value.companyId = userStore.userInfo.companyId  // 地块id列表
    // 循环取出已经选择的地块id，放入landIds中
    landSelectData.value.forEach(item =>{
        formdata.value.headerLandIdList.push(item.curLand.farmLandId)
    })
    if(!formdata.value.yield){
        return message('请输入每亩目标产量',3)
    }else if(!formdata.value.cropId){
        return message('请选择作物',3)
    }else if(!formdata.value.category){
        return message('请输入品种',3)
    }
    // else if(formdata.value.headerLandIdList.length<1){
    //     return message('请选择种植地块',3)
    // }
    
    console.log("stages:",stages.value)
    // 组装参数
    formdata.value.lineList = []
    for(let i=0;i<stages.value.length;i++){
        const stagesItem = stages.value[i]
        for(let j=0;j<stagesItem.lineList.length;j++){
            const lineListItem = stagesItem.lineList[j]
            if(lineListItem.lineLandIdList && lineListItem.lineLandIdList.length>0){ // 选择了地块
                // let fuzeUserList = []
                // // 组装负责人
                // lineListItem.fuzeUserIds.forEach(ele =>{
                //     const uit = userList.value.find(it => it.valueCode==ele)
                //     const obj = {
                //         fuzeRealName:uit.meaning,
                //         fuzeUserId:ele
                //     }
                //     fuzeUserList.push(obj)
                // })
                
                let lineListObj = {
                    budgetFee:lineListItem.budgetFee,
                    farmId:lineListItem.farmId,
                    fuzeUserIdList:lineListItem.fuzeUserIds,//fuzeUserList,
                    lineLandIdList:lineListItem.lineLandIdList,
                    reason:lineListItem.reason || '',
                    stageId:stagesItem.stageId,  // 种植阶段id
                    stageTaskId:lineListItem.stageTaskId,  // 任务id
                    taskContent:lineListItem.taskContent,
                    taskEndTime:lineListItem.time[1],
                    taskStartTime:lineListItem.time[0],
                    taskStatus:lineListItem.taskStatus || ''
                }
                if(plantHeaderId.value){ // 编辑
                    lineListObj.plantLineId = lineListItem.plantLineId
                }
                formdata.value.lineList.push(lineListObj)
            }  
        }
    }
    console.log("表单信息：",formdata.value)
 
    let res = {}
    if(plantHeaderId.value){ // 编辑
        formdata.value.plantHeaderId = plantHeaderId.value
        res = await editFarmPlant(formdata.value)
    }else{
        res = await addFarmPlant(formdata.value)
    }
    
    if(res.code ==0 || res.success){
        message('数据提交成功',2)
        close()  // 关闭当前页
        emitter.emit('reload') // 刷新页面
    }else{
        message(res.message || '数据提交失败',3)
    }
  }
 
  const delLineListItem = (lineList,index)=>{

    if(plantHeaderId.value && lineList[index].taskStatus){
        dialogFlag.value = true
        dialogInfo.value.title = "提示"
        dialogInfo.value.type = 3
        dialogInfo.value.options = lineList[index]
        dialogInfo.value.width = '500px'
    }else{
        lineList.splice(index,1)
    }
  }

  const openSelectDg = (stagesItem,lineListItem) =>{
    dialogFlag.value = true
    dialogInfo.value.title = "选择地块"
    dialogInfo.value.type = 4
    dialogInfo.value.options = {stagesItem,lineListItem}
    dialogInfo.value.width = '900px'
  }
  
  const close = ()=>{
    emitter.emit('closeThisPage')
  }
  
  </script>
  
  <style lang="scss">
    .plantFormBox{
        margin: -20px 0 0 -10px;
       .formItem{
            &+.formItem{
                margin-top: 20px;
            }
            h5{
                display: flex;
                font-size: 12px;
                align-items: center;
                height: 26px;
                margin: 0;
                padding: 0;
                &::before{
                    content: '';
                    display: block;
                    width: 3px;
                    background: #48b27a;
                    height: 14px;
                    margin: 0 3px 0 0;
                }
                span{
                    font-weight: normal;
                }
            }
            .inputItem{
                display: flex;
                align-items: center;
                margin: 5px 0 0 0;
                .lable{
                    flex-shrink: 0;
                    span{
                        color: #f70808;
                    }
                }
            }
            .mytips{
                font-size: 12px;
                color: #999;
                -ms-transform:scale(0.95); /* IE 9 */
                -webkit-transform: scale(0.95); /* Safari */
                transform: scale(0.95); /* 标准语法 */
                -webkit-origin: 0 0;
                transform-origin:0 0 ;
                margin: 10px 0 10px 0;
            }
            .itemTableBox{
                width: 100%;
                min-width: 1150px;
                border: 1px solid #e6e4e4;
                border-collapse:collapse ;
                th,td{
                    text-align: left; 
                    span{
                        color: #f70808;
                    }
                }
                th{
                    background-color: #e6e4e4;
                    height: 30px;
                    padding: 0 8px;
                    &+th{
                        border-left: 1px solid #e6e4e4;
                    }
                }
                td{
                    text-align: left;
                    padding:6px 8px;
                    border-top: 1px solid #e6e4e4;
                    &+td{
                        border-left: 1px solid #e6e4e4;   
                    }
                    
                }
                .tbItemFlex{
                    display: flex;
                    align-items: center;
                    .el-icon{
                        cursor: pointer;
                        &:hover{

                        }
                    }
                }
            }
       } 
       .cbjs{
        padding: 15px 0 0 0;
        b{
            font-size: 16px;
        }
       }
    }
  </style>

  <style lang="scss">
    .plantFormBox{
        .el-input__inner{
            font-size: 12px!important;
        }
        .mydaterange{
            width: 330px;
            input{
                font-size: 12px!important;
            }
        }
        .el-input--suffix{
            i{
                color: #999!important;
            }
        }
    }
</style>
  